#include "SharedCounter.h"

const std::string SharedCounter::default_path = "SharedCounter";


SharedCounter::SharedCounter() : counter(), mutex(NULL)
{
}

SharedCounter::SharedCounter(const std::string& file_path, char letra) :
		counter(file_path, letra)
{
	key_t key = ftok(file_path.c_str(), letra);
	if (key == -1)
		throw std::string("Error al generar la clave.");
	mutex = new Semaforo(key);
}

SharedCounter::~SharedCounter() {
	delete mutex;
}

void SharedCounter::create(const std::string& file_path, const char letra)
{
	counter.crear(file_path, letra);
	if(mutex == NULL)
	{
		key_t key = ftok(file_path.c_str(), letra);
		if (key == -1)
			throw std::string("Error al generar la clave.");
		mutex = new Semaforo(key);
	}
}

void SharedCounter::increment(int inc)
{
	if(mutex)
		mutex->p();
	int value = counter.leer() + inc;
	counter.escribir(value);
	if(mutex)
		mutex->v();
}

void SharedCounter::decrement(int dec)
{
	if(mutex)
		mutex->p();
	int value = counter.leer() - dec;
	counter.escribir(value);
	if(mutex)
		mutex->v();
}

void SharedCounter::free_()
{
	counter.liberar();
}

void SharedCounter::deleteMutex()
{
	if (mutex) {
		mutex->eliminar();
		delete mutex;
		mutex = NULL;
	}
}

void SharedCounter::init(SharedCounter & counter) {
	if (counter.mutex)
		counter.mutex->setVal(1);
	counter.counter.escribir(0);
}

int SharedCounter::reed() {
	if(mutex)
		mutex->p();
	int value = counter.leer();
	if(mutex)
		mutex->v();
	return value;
}
